package com.xpp.yanbi.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xpp.yanbi.annotation.AuthCheck;
import com.xpp.yanbi.bimq.BiMessageProducer;
import com.xpp.yanbi.bimq.MyMessageProducer;
import com.xpp.yanbi.common.BaseResponse;
import com.xpp.yanbi.common.DeleteRequest;
import com.xpp.yanbi.common.ErrorCode;
import com.xpp.yanbi.common.ResultUtils;
import com.xpp.yanbi.constant.UserConstant;
import com.xpp.yanbi.exception.BusinessException;
import com.xpp.yanbi.exception.ThrowUtils;
import com.xpp.yanbi.manager.MoonshotAiService;
import com.xpp.yanbi.manager.RedisLimiterManager;
import com.xpp.yanbi.model.dto.chart.*;
import com.xpp.yanbi.model.enity.Chart;
import com.xpp.yanbi.model.enity.User;
import com.xpp.yanbi.model.vo.BiResponse;
import com.xpp.yanbi.service.ChartService;
import com.xpp.yanbi.service.UserService;
import com.xpp.yanbi.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 *
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {
    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private MoonshotAiService moonshotAiService;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiMessageProducer biMessageProducer;

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        // chartService.validChart(chart, true);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());

        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);

        // 参数校验
        // chartService.validPost(chart, false);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                     HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion


    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        // 参数校验
        // postService.validPost(post, false);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * ai智能分析（同步）
     *
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genCharByBi(@RequestPart("file") MultipartFile multipartFile,
                                                GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {
        String name = genChartByAIRequest.getName();
        String goal = genChartByAIRequest.getGoal();
        String chartType = genChartByAIRequest.getChartType();

        User loginUser = userService.getLoginUser(request);
        redisLimiterManager.doRateLimit("genCharByBi_" + loginUser.getId());
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) || name.length() > 100, ErrorCode.PARAMS_ERROR, "名称为空");

        // 校验文件
        long fileSize = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(ONE_MB < fileSize, ErrorCode.PARAMS_ERROR, "文件超过 1MB");
        // final List<String> validFileSuffixList = Arrays.asList("png","jpg","svg","webp","jpeg","xlsx");
        final List<String> validFileSuffixList = Arrays.asList("xlsx","xls");
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件非法后缀");

        // 拼接分析需求
        if (StringUtils.isNotBlank(chartType)) {
            goal += ". 请使用 " + chartType + "图片类型.";
        }

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求: ").append(goal).append("\n");

        // 压缩数据
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据: ").append(csvData).append("\n");
        String aiContent = moonshotAiService.doChat(userInput.toString());
        String[] splits = aiContent.split("【【【【【【【");
        if (splits.length < 3) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "ai 响应结果异常");
        }
        String genChart = splits[1];
        String genResult = splits[2];

        // 插入到数据库
        Chart chart = new Chart();
        chart.setUserId(loginUser.getId());
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表数据保存失败");

        // 构建响应
        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);

        return ResultUtils.success(biResponse);
    }


    /**
     * ai智能分析 (异步)
     *
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/Async")
    public BaseResponse<BiResponse> genCharByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                     GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {
        String name = genChartByAIRequest.getName();
        String goal = genChartByAIRequest.getGoal();
        String chartType = genChartByAIRequest.getChartType();

        User loginUser = userService.getLoginUser(request);
        redisLimiterManager.doRateLimit("genCharByBi_" + loginUser.getId());
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) || name.length() > 100, ErrorCode.PARAMS_ERROR, "名称为空");

        // 校验文件
        long fileSize = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();

        // 校验文件大小
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(ONE_MB < fileSize, ErrorCode.PARAMS_ERROR, "文件超过 1MB");
        // final List<String> validFileSuffixList = Arrays.asList("png","jpg","svg","webp","jpeg","xlsx");
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件非法后缀");

        // 拼接分析需求
        if (StringUtils.isNotBlank(chartType)) {
            goal += ". 请使用 " + chartType + "图片类型.";
        }

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求: ").append(goal).append("\n");

        // 压缩数据
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据: ").append(csvData).append("\n");

        // 插入到数据库
        Chart chart = new Chart();
        chart.setUserId(loginUser.getId());
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        // chart.setGenChart(genChart);
        // chart.setGenResult(genResult);
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表数据保存失败");

        // 异步化
        CompletableFuture.runAsync(() -> {
            // 先修改图表 状态为 "执行中"
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus("running");
            boolean result = chartService.updateById(updateChart);
            if (!result) {
                handleChartUpdateError(chart.getId(),"更新图表执行中状态失败");
                return;
            }
            // ai处理
            String aiContent = moonshotAiService.doChat(userInput.toString());
            String[] splits = aiContent.split("【【【【【【【");
            if (splits.length < 3) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "ai 响应结果异常");
            }
            String genChart = splits[1];
            String genResult = splits[2];
            // 得到ai结果 再更新
            updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setGenChart(genChart);
            updateChart.setGenResult(genResult);
            updateChart.setStatus("succeed");
            boolean b = chartService.updateById(updateChart);
            if (!b) {
                handleChartUpdateError(chart.getId(),"更新图表成功状态失败");
            }
        }, threadPoolExecutor);


        // 构建响应
        BiResponse biResponse = new BiResponse();
        // biResponse.setGenChart(genChart);
        // biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());

        return ResultUtils.success(biResponse);
    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus("failed");
        chart.setExecMessage(execMessage);
        boolean result = chartService.updateById(chart);
        if (!result) {
            log.error("更新图表状态失败," + chartId + ", " + execMessage);
        }
    }


    /**
     * ai智能分析 (RabbitMQ)
     *
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/mq")
    public BaseResponse<BiResponse> genCharByAiMQ(@RequestPart("file") MultipartFile multipartFile,
                                                     GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {
        String name = genChartByAIRequest.getName();
        String goal = genChartByAIRequest.getGoal();
        String chartType = genChartByAIRequest.getChartType();

        User loginUser = userService.getLoginUser(request);
        redisLimiterManager.doRateLimit("genCharByBi_" + loginUser.getId());
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isBlank(name) || name.length() > 100, ErrorCode.PARAMS_ERROR, "名称为空");

        // 校验文件
        long fileSize = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();

        // 校验文件大小
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(ONE_MB < fileSize, ErrorCode.PARAMS_ERROR, "文件超过 1MB");
        // final List<String> validFileSuffixList = Arrays.asList("png","jpg","svg","webp","jpeg","xlsx");
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件非法后缀");

        // 拼接分析需求
        if (StringUtils.isNotBlank(chartType)) {
            goal += ". 请使用 " + chartType + "图片类型.";
        }

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求: ").append(goal).append("\n");

        // 压缩数据
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据: ").append(csvData).append("\n");

        // 插入到数据库
        Chart chart = new Chart();
        chart.setUserId(loginUser.getId());
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        // chart.setGenChart(genChart);
        // chart.setGenResult(genResult);
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表数据保存失败");
        // 异步化
        CompletableFuture.runAsync(() -> {
            biMessageProducer.sendMessage(String.valueOf(chart.getId()));
        }, threadPoolExecutor);
        // 构建响应
        BiResponse biResponse = new BiResponse();
        // biResponse.setGenChart(genChart);
        // biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());

        return ResultUtils.success(biResponse);
    }

}
